package com.da.javatest.thread.task;

import org.slf4j.LoggerFactory;

import java.util.function.Consumer;

public class ExceptionHandler {

    static public final org.slf4j.Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    public static void ignore(FunctionWithException func) {
        simple(func, (e) -> logger.error("ignore error. ", e));
    }

    public static void ignoreNoLog(FunctionWithException func) {
        simple(func, (e) -> {
        });
    }

    public static void simple(FunctionWithException func, Consumer<Exception> handler) {
        try {
            func.execute();
        } catch (Exception e) {
            handler.accept(e);
            //if (WDKException.class.isInstance(e)) {
            //    WDKException exception = (WDKException)e;
            //    exception.log();
            //}
        }
    }

    public static <T> T ignoreWithReturn(ResultFunctionWithException<T> func) {
        return simpleWithReturn(func, (e) -> logger.error("ignore error. ", e));
    }

    public static <T> T ignoreWithReturnNoLog(ResultFunctionWithException<T> func) {
        return simpleWithReturn(func, (e) -> {
        });
    }

    public static <T> T ignoreWithReturn(ResultFunctionWithException<T> func, T errorRes) {
        return simpleWithReturn(func, (e) -> logger.error("ignore error. ", e), errorRes);
    }

    public static <T> T simpleWithReturn(ResultFunctionWithException<T> func, Consumer<Exception> handler) {
        return simpleWithReturn(func, handler, null);
    }

    public static <T> T simpleWithReturn(ResultFunctionWithException<T> func, Consumer<Exception> handler, T errorRes) {
        try {
            return func.execute();
        } catch (Exception e) {
            //logger.error("simple error. ", e);
            handler.accept(e);
            //if (WDKException.class.isInstance(e)) {
            //    WDKException exception = (WDKException)e;
            //    exception.log();
            //}
        }
        return errorRes;
    }

    public static void throwException(FunctionWithException func) {
        simple(func, (e) -> {
            logger.error("throwException error. ", e);
            if (e instanceof RuntimeException) {
                throw (RuntimeException)e;
            }
            throw new RuntimeException(e);
        });
    }

    public static <T> T throwExceptionWithReturn(ResultFunctionWithException<T> func) {
        return simpleWithReturn(func, (e) -> {
            logger.error("throwException error. ", e);
            if (e instanceof RuntimeException) {
                throw (RuntimeException)e;
            }
            throw new RuntimeException(e);
        });
    }

}
